using System;
using System.Web;
using System.Web.UI;

using ContinualFlame.Ajax;

namespace ContinualFlame.Locus
{	
	public class ClientEventStream : System.Web.IHttpHandler
	{	
		public virtual bool IsReusable
		{
			get
			{
				return false;
			}
		}
		
		public virtual void ProcessRequest(HttpContext context)
		{
			HttpRequest req = context.Request;
            HttpResponse rsp = context.Response;

            if (req.HttpMethod == "GET")
            {
				string sid = req.Params["id"];
				int watermark = Int32.Parse(req.Params["watermark"]);
				string cid = req.Cookies.Get(ContinualFlame.Locus.Session.SessionCookieName).Value;
				
				//
				// auth check
				//
				
				Session s = SessionManager.Instance.GetSessionById(sid);
				
				if (!s.AuthorizedClients.ContainsKey(cid))
				{
					// TODO: the cool kids would return a meaningful error code
					throw new ApplicationException("Unknown user or session. Has your game expired?");
				}

				ClientConnection conn = new ClientConnection(rsp);
				s.SyncManager.RegisterClient(watermark, cid, conn);
				
				try
				{	
					// hang forever and pump messages to the client
					// TODO: should be more clever with our HTTP thread worker pool
					conn.WaitForExit();
				}
				finally
				{
					s.SyncManager.UnregisterClient(cid);
				}
				
			}
			else
			{
				// TODO: the cool kids would return a meaningful error code
				throw new ApplicationException("invalid HTTP method: only GET is supported.");
			}
		}
	}
}
